import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyEncrptyUtil.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyRegUtil.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyUserUtil.dart';
import 'package:ecy_app_flutter/main.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import '../../EcyRouter.dart';
import '../../constant/color_constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../constant/constant.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyJPushUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';
import '../mainTabPage.dart';
import 'common/CustomTextFieldWidget.dart';

class EcyVerificationCodeLoginPage extends EcyCommonBaseWidget {
  EcyVerificationCodeLoginPage();

  @override
  _EcyVerificationCodeLoginPage createState() {
    return _EcyVerificationCodeLoginPage(this);
  }
}

class _EcyVerificationCodeLoginPage extends EcyCommonBaseWidgetState
    with SingleTickerProviderStateMixin {
  String mobile = "";
  String code = "";
  int left = 60;
  bool checked = false;
  bool canNext = false;
  bool loadingFlag = false;
  late EcyCommonBaseWidget controller;
  _EcyVerificationCodeLoginPage(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  @override
  void initState() {
    super.initState();
  }

  //private
  void onUpdateMobile(String newValue) {
    setState(() {
      mobile = newValue;
      checkCondtions();
    });
  }

  void onUpdateCode(String newValue) {
    setState(() {
      code = newValue;
      checkCondtions();
    });
  }

  void checkCondtions() {
    if (mobile.length == 11 && code.length == 6) {
      canNext = true;
    } else {
      canNext = false;
    }
  }

  void sendSMS() async {
    if (!EcyRegUtil.validTel(mobile)) {
      EasyLoading.showToast("请输入11位合法手机号",
          duration: const Duration(seconds: 2));
      return;
    }

    Timer timer = countDown();

    Map<String, dynamic> body = {};
    body["tel"] = mobile;
    body["type"] = "0";
    var response =
        await EcyRequestbasemanager().get("/app/api/app/user/sms", body);
    controller.dismissLoading();
    if (response != null) {
      setState(() {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          String msg = "发送成功";
          if ((resp.code != 0 && resp.code != 200)) {
            msg = resp.msg ?? "";
            timer.cancel();
            setState(() {
              left = 60;
            });
          }
          EasyLoading.showToast(msg, duration: const Duration(seconds: 2));
        }
      });
    }
  }

  void registerAndLogin() async {
    if (loadingFlag) {
      return;
    }

    _loading();

    Map<String, dynamic> body = {};
    body["username"] = mobile;
    body["password"] = EcyEncrptyUtil.aesEncode(code);
    body["loginType"] = "1";
    body["pushId"] = await EcyJPushUtil.getRegistrationID();
    body["clientType"] = Platform.isAndroid ? 0 : 1;

    try {
      var response =
          await EcyRequestbasemanager().post("/app/api/app/user/login", body);
      if (response != null) {
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          if (resp.code == 0 || resp.code == 200) {
            EcyUserModel user = EcyUserModel.fromJson(response["data"]);
            EcyUserUtil.saveLoginedData(user);
            Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(
                  builder: (context) => ContainPage(
                        key: const Key("containPage"),
                        appLinks: gAppLinks,
                      )),
              (Route<dynamic> route) => false,
            );
          } else {
            EasyLoading.showToast(resp.msg ?? Constant.NET_ERROR,
                duration: const Duration(seconds: 2));
          }
        } else {
          EasyLoading.showToast(Constant.NET_ERROR);
        }
      } else {
        EasyLoading.showToast(Constant.NET_ERROR);
      }
    } catch (e) {
      EasyLoading.showToast(Constant.NET_ERROR);
    } finally {
      setState(() {
        loadingFlag = false;
      });
    }
  }

  _loading() {
    setState(() {
      loadingFlag = true;
    });
  }

  Timer countDown() {
    return Timer.periodic(const Duration(seconds: 1), (Timer t) {
      if (left == 0) {
        t.cancel();
        setState(() {
          left = 60;
        });
      } else {
        var _left = left - 1;
        setState(() {
          left = _left;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: KeyboardDismisser(
            gestures: const [
              GestureType.onTap,
              GestureType.onPanUpdateDownDirection
            ],
            child: Scaffold(
                resizeToAvoidBottomInset: false,
                backgroundColor: ColorConstant.White,
                appBar: AppBar(
                  toolbarHeight: 40.h,
                  backgroundColor: ColorConstant.White,
                  title: Text(title),
                ),
                body: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      height: 50.h,
                    ),
                    Image(
                        image: const AssetImage(
                            'assets/images/login_app_icon.png'),
                        width: 80.w,
                        height: 80.w),
                    SizedBox(
                        width: MediaQuery.of(context).size.width, height: 45.h),
                    Wrap(
                      alignment: WrapAlignment.center,
                      direction: Axis.horizontal,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      spacing: 0,
                      children: [
                        Image(
                            image: const AssetImage(
                                'assets/images/ic_login_account.png'),
                            width: 24.w,
                            height: 24.w),
                        SizedBox(
                          width: MediaQuery.of(context).size.width - 60.w,
                          height: 36.h,
                          child: CustomTextFieldWidget(
                            hint: "请输入手机号",
                            inputValue: mobile,
                            updateMessageCallback2: onUpdateMobile,
                            textInputFormatterList: [
                              FilteringTextInputFormatter.digitsOnly,
                              LengthLimitingTextInputFormatter(11)
                            ],
                            keyboardType: TextInputType.phone,
                            obscureText: false,
                          ),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 10.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 16.w, right: 0, top: 25.h, bottom: 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Image(
                              image: const AssetImage(
                                  'assets/images/ic_login_pwd.png'),
                              width: 24.w,
                              height: 24.w),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 170.w,
                            height: 36.h,
                            child: CustomTextFieldWidget(
                              hint: "请输入验证码",
                              inputValue: code,
                              updateMessageCallback2: onUpdateCode,
                              textInputFormatterList: [
                                FilteringTextInputFormatter.digitsOnly,
                                LengthLimitingTextInputFormatter(6)
                              ],
                              keyboardType: TextInputType.number,
                              obscureText: false,
                            ),
                          ),
                          GestureDetector(
                              onTap: () {
                                if (left != 60) {
                                } else {
                                  sendSMS();
                                }
                              },
                              child: Container(
                                width: 116.w,
                                height: 42.h,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(26),
                                    border: Border.all(
                                        color: left == 60
                                            ? const Color(0xFFEA4B9B)
                                            : const Color(0xFFBFBFBF),
                                        width: 1.w)),
                                child: Center(
                                  child: Text(
                                      (left == 60 ? "发送验证码" : ("${left}s后重发")),
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 16,
                                          color: (left == 60
                                              ? const Color(0xFFEA4B9B)
                                              : const Color(0xFFBFBFBF)))),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 10.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    GestureDetector(
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          if (!EcyRegUtil.validTel(mobile)) {
                            EasyLoading.showToast("请输入正确的手机号",
                                toastPosition: EasyLoadingToastPosition.center,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (code.isEmpty) {
                            EasyLoading.showToast("请输入验证码",
                                toastPosition: EasyLoadingToastPosition.center,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (!checked) {
                            EasyLoading.showToast("请先勾选协议",
                                toastPosition: EasyLoadingToastPosition.center,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          registerAndLogin();
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(26.r),
                            color: ColorConstant.CommonColor,
                          ),
                          margin: EdgeInsets.only(
                              left: 22, right: 22, top: 57.h, bottom: 10.0),
                          width: MediaQuery.of(context).size.width - 44.w,
                          height: 52.h,
                          alignment: Alignment.center,
                          child: Stack(
                            children: [
                              SizedBox(
                                height: 45.h,
                                width: 45.w,
                                child: Align(
                                  alignment: Alignment.center,
                                  child: Transform.translate(
                                    offset: const Offset(-35.0, 0.0),
                                    child: loadingFlag
                                        ? Image.asset(
                                        width: 28.w,
                                        height: 25.h,
                                        alignment: Alignment.center,
                                        "assets/images/loading/loading.gif")
                                        : null,
                                  ),
                                ),
                              ),
                              SizedBox(
                                  height: 45.h,
                                  width: 45.w,
                                  child: Align(
                                    alignment: Alignment.center,
                                    child: Text('登录',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 18.sp,
                                            color: ColorConstant.White)),
                                  )),
                            ],
                          ),
                        )),
                    Expanded(
                      child: Container(
                        color: Colors.transparent,
                      ),
                    ),
                    Wrap(
                      direction: Axis.horizontal,
                      spacing: 0,
                      children: [
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () => {
                            setState(() {
                              checked = !checked;
                            }),
                          },
                          child: Image(
                              image: AssetImage(checked
                                  ? 'assets/images/login_checked.png'
                                  : 'assets/images/login_unchecked.png'),
                              width: 22.w,
                              height: 22.w),
                        ),
                        SizedBox(
                          width: MediaQuery.of(context).size.width - 40.w,
                          child: GestureDetector(
                            onTap: () {},
                            child: Padding(
                                padding: const EdgeInsets.only(top: 3),
                                child: RichText(
                                  text: TextSpan(
                                    children: [
                                      TextSpan(
                                        text: ' 已详细阅读并同意',
                                        style: TextStyle(
                                            color: const Color.fromARGB(
                                                255, 140, 140, 140),
                                            fontSize: 12.sp),
                                      ),
                                      TextSpan(
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () {
                                              EcyRouter.pushNoParams(context,
                                                  EcyRouter.privacyPolicyPage);
                                            },
                                          text: '《使用条款和个人信息保护政策》',
                                          style: TextStyle(
                                              color: ColorConstant.CommonColor,
                                              fontSize: 12.sp)),
                                    ],
                                  ),
                                )),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                        width: MediaQuery.of(context).size.width, height: 40.h),
                  ],
                ))),
        onTap: () {
          //触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        });
  }
}

class MyTextFieldWidget extends StatefulWidget {
  final String inputValue;
  final String hint;
  final ValueChanged<String> updateMessageCallback2;
  MyTextFieldWidget(
      {required this.hint,
      required this.inputValue,
      required this.updateMessageCallback2});

  @override
  _MyTextFieldWidgetState createState() => _MyTextFieldWidgetState(
      hint: hint,
      inputValue: inputValue,
      updateMessageCallback: updateMessageCallback2);
}

class _MyTextFieldWidgetState extends State<MyTextFieldWidget> {
  final String inputValue;
  final String hint;
  ValueChanged<String> updateMessageCallback;
  _MyTextFieldWidgetState(
      {required this.hint,
      required this.inputValue,
      required this.updateMessageCallback});
  @override
  Widget build(BuildContext context) {
    return TextField(
        inputFormatters: [
          FilteringTextInputFormatter.digitsOnly,
          LengthLimitingTextInputFormatter(11)
        ],
        decoration: InputDecoration(
            isDense: true,
            border: InputBorder.none, // 移除默认边框
            focusedBorder: const UnderlineInputBorder(
              // 获取焦点时的下划线
              borderSide: BorderSide(
                color: ColorConstant.CommonColorWhite, // 修改下划线颜色
                width: 0, // 修改下划线宽度
              ),
            ),
            enabledBorder: const UnderlineInputBorder(
              // 默认状态下的下划线
              borderSide: BorderSide(
                color: ColorConstant.CommonColorWhite, // 修改下划线颜色
                width: .0, // 修改下划线宽度
              ),
            ),
            hintText: hint,
            hintStyle: const TextStyle(
                fontFamily: "PingFag SC",
                fontWeight: FontWeight.w500,
                fontSize: 16,
                color: ColorConstant.CommonColorGray)),
        textAlign: TextAlign.start,
        style: TextStyle(
            fontFamily: "PingFag SC",
            fontWeight: FontWeight.w700,
            fontSize: 18.sp,
            color: ColorConstant.CommonColorBlack),
        onEditingComplete: () {
          // 当用户点击完成按钮时，这个函数会被调用;
          // 你可以在这里添加你的逻辑，比如验证输入或提交数据
        },
        onSubmitted: (value) {
          FocusScope.of(context).unfocus();
        },
        onChanged: (value) {
          // 这个回调函数会在文本变化时不断被调用
          print('文本变化: $value');
          updateMessageCallback(value);
        });
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
  }
}
